package com.ruoyi.wechat.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wechat.domain.BackTextInfo;
import com.ruoyi.wechat.domain.WeChatXmlData;
import com.ruoyi.wechat.domain.WeChatRequest;
import com.ruoyi.wechat.service.ReceiveWechatService;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;

/**
 * 接收微信消息 Controller
 * @author zyj
 * @date 2022-08-22 14:19
 */
@RestController
@RequestMapping("/weChat")
public class ReceiveWxController {

    private static final String TOKEN = "3I8lC09DZPa95trMVUzfnaSc";

    private Logger logger= LoggerFactory.getLogger(ReceiveWxController.class);

    @Autowired
    private ReceiveWechatService receiveWechatService;


    /**
     * 微信调用此接口 发送信息
     * @param request
     * @param response
     * @throws Exception
     */
    @Anonymous
    @RequestMapping(value="/receiveWx",method= RequestMethod.POST,consumes = {MediaType.TEXT_XML_VALUE},produces = {MediaType.APPLICATION_JSON_VALUE})
    public void receiveWxToken(WeChatRequest weChatRequest, @RequestBody WeChatXmlData weChatXmlData, HttpServletResponse resp) throws Exception{
        logger.debug("收到微信消息,{}", JSON.toJSONString(weChatRequest));
        logger.debug("收到地址定位微信消息,{}", JSON.toJSONString(weChatXmlData));
        resp.setCharacterEncoding("UTF-8");
        String[] params = new String[]{weChatRequest.getNonce(),weChatRequest.getTimestamp(),TOKEN};
        Arrays.sort(params);
        String signatureResult = DigestUtils.sha1Hex(params[0]+params[1] + params[2]);
        //校验签名
        if(!signatureResult.equals(weChatRequest.getSignature())) {
            throw new RuntimeException("signature is not the same wechat signature is " + weChatRequest.getSignature() + " signatureResult is " + signatureResult);
        }
        XStream xStream =new XStream();
        BackTextInfo backTextInfo = receiveWechatService.execWechatXmlData(weChatXmlData);
        PrintWriter writer = resp.getWriter();
        if(backTextInfo!=null){
            xStream.alias("xml", BackTextInfo.class);
            writer.write(xStream.toXML(backTextInfo));
        }else {
            writer.write("success");
        }
        writer.flush();
        writer.close();
    }


//    @Anonymous
//    @RequestMapping("/receiveWx")
//    public void receiveWxToken(HttpServletRequest request, HttpServletResponse response) throws Exception{
//
//        String signature = request.getParameter("signature");
//        String timestamp = request.getParameter("timestamp");
//        String nonce = request.getParameter("nonce");
//        String echostr = request.getParameter("echostr");
//        System.out.println("signature: " + signature);
//        System.out.println("timestamp: " + timestamp);
//        System.out.println("nonce: " + nonce);
//        System.out.println("echostr: " + echostr);
//        String[] params = new String[]{nonce,timestamp,TOKEN};
//        Arrays.sort(params);
//        String signatureResult = DigestUtils.sha1Hex(params[0]+params[1] + params[2]);
//        //校验签名
//        if(!signatureResult.equals(signature)) {
//            throw new RuntimeException("signature is not the same wechat signature is " + signature + " signatureResult is " + signatureResult);
//        }
//        response.getWriter().write(echostr);
//    }

}
